package com.wsj.util.tool;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import sun.misc.BASE64Decoder;
/**
 *
 * @author Zhang Yu
 *
 */
 
public class DiscuzPassport extends HibernateDaoSupport 
{
	
	//定义用户类型头 ,个人表
	public static final String geren="g_";
	
	//企业表
	public static final  String qiye="q_";
	
	//系统管理员
	public static final  String guanliyuan="a_";
	
	//密钥
	public static final String qqddcKey="qqddcebb365";
	
	//jdbc模板
	private JdbcTemplate jdbcTemplateForBBS;
 
 public static String encrypt(String src, String key) {
  Random random = new Random();
  random.setSeed(System.currentTimeMillis());
  String rand = "" + random.nextInt() % 32000;
  String encKey = DiscuzEncryption.generateKey(rand, "MD5");
  int ctr = 0;
  String tmp = "";
  for (int i = 0; i < src.length(); i++) {
   ctr = (ctr == encKey.length() ? 0 : ctr);
   tmp += encKey.charAt(ctr);
   char c = (char) (src.charAt(i) ^ encKey.charAt(ctr));
   tmp += c;
   ctr++;
  }
  String passportKey = passportKey(tmp, key);
  return new sun.misc.BASE64Encoder().encode(passportKey.getBytes());
 }
 
 public static String decrypt(String src, String key) {
  byte[] bytes = null;
  try {
   bytes = new BASE64Decoder().decodeBuffer(src);
   src = new String(bytes);
  } catch (Exception e) {
   return null;
  }
  src = passportKey(src, key);
  String tmp = "";
  for (int i = 0; i < src.length(); ++i) {
   char c = (char) (src.charAt(i) ^ src.charAt(++i));
   tmp += c;
  }
  return tmp;
 }
 
 public static String passportKey(String src, String key) {
  String encKey = DiscuzEncryption.generateKey(key, "MD5");
  int ctr = 0;
  String tmp = "";
  for (int i = 0; i < src.length(); ++i) {
   ctr = (ctr == encKey.length() ? 0 : ctr);
   char c = (char) (src.charAt(i) ^ encKey.charAt(ctr));
   tmp += c;
   ctr++;
  }
  return tmp;
 }
 
 public static String passportEncode(Map data) {
  Set keys = data.keySet();
  String key = "";
  String ret = "";
  Iterator iterator = keys.iterator();
  while (iterator.hasNext()) {
   key = (String) iterator.next();
   try
   {
    ret += key + "=" + (String) data.get(key) + "&";
   }
   catch (Exception e)
   {
    return "";
   }
  }
  if (ret.length() > 0)
   return ret.substring(0, ret.length() - 1);
  return "";
 }
 
 /*******
  * 发送用户登陆信息
  * @param arg
  * userType 是用户类型的头 比如 u_  , a_ , q_
  */
 public String userBBSLogin(String userType,String bbsUsernameHomesite,String bbsPassword,String email,String backPage,HttpServletRequest request,HttpServletResponse response)
 {
	  
	 try {
		 
		    String bbsUsername=userType+bbsUsernameHomesite;
		    //先检测用户是否已经存在于bbs数据库中.
		    boolean isok=this.checkBBSUser(bbsUsername);
		    if(!isok)
		    {
		    	//执行将数据插入到bbs库中
		    	userBBSRegister(userType,bbsUsernameHomesite, bbsPassword, email, request, response);
		    }
		 
		    Map mb = new LinkedHashMap();
			mb.put("time", "" + System.currentTimeMillis());
			mb.put("username", bbsUsername);
			mb.put("password", bbsPassword);
			mb.put("email", email);
			String key = qqddcKey; //私钥
			String enc=DiscuzPassport.passportEncode(mb);
			String auth = DiscuzPassport.encrypt(enc, key);
			//返回页面.
			String forward=backPage;
			String verifyParent = "login" + auth + forward + key;
			String verify = DiscuzEncryption.generateKey(verifyParent, "MD5"); 

			StringBuffer locationBuf = new StringBuffer("/bbs/api/passport.php?action=login&auth=").append(java.net.URLEncoder.encode(auth, "UTF-8")) 
			.append("&forward=").append(java.net.URLEncoder.encode(forward, "UTF-8")).append("&verify=" + verify);
			
			//将这个链接发送出去.
//			URL url = new URL(locationBuf.toString());
//			HttpURLConnection urlConnection  = (HttpURLConnection)url.openConnection();
			
			return locationBuf.toString();
			
			//response.sendRedirect(locationBuf.toString());
			
	} catch (UnsupportedEncodingException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	
	return  "http://www.qqddc.com";
	 
 }
 
 
 /*****
  * 检测用户名,是否在bbs中存在.
  * @param bbsUsername
  * @return
  */
 private boolean checkBBSUser(String bbsUsername) 
 {
	boolean isok=false;
    StringBuffer checkUserSql=new StringBuffer("select uid from cdb_members where username= '"+bbsUsername+"'");
    List li=this.getJdbcTemplateForBBS().queryForList(checkUserSql.toString());
    if(li!=null && !li.isEmpty())
    {
    	isok = true;
    }
    
    return isok;
 }

/*********
  * 用户退出
  */
 public String userBBSLoginOut(String userType,String bbsUsernameHomeSite,String bbsPassword,String email,String backPage,HttpServletRequest request,HttpServletResponse response)
 {
	 
	    try {
	    	String bbsUsername = userType +bbsUsernameHomeSite;
			Map mb = new LinkedHashMap();
			mb.put("time", "" + System.currentTimeMillis());
			mb.put("username", bbsUsername);
			mb.put("password", bbsPassword);
			mb.put("email", email);
			String key = qqddcKey; //私钥
			String enc=DiscuzPassport.passportEncode(mb);
			String auth = DiscuzPassport.encrypt(enc, key);
			//返回页面.
			String forward=backPage;
			String verifyOut = "logout"  + forward + key;
			verifyOut = DiscuzEncryption.generateKey(verifyOut,"MD5");
			
			StringBuffer locationBuf = new StringBuffer("/bbs/api/passport.php?action=logout"+ "&forward=" + java.net.URLEncoder.encode(forward, "UTF-8") + "&verify=" + verifyOut);
			
			//response.sendRedirect(locationBuf.toString());
			
			return locationBuf.toString();
			
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "http://www.qqddc.com";
 }
 
 
 /*******
  * bbs用户同步注册
  */
 public boolean userBBSRegister(String userType,String bbsUsernameHomeSite,String bbsPassword,String email,HttpServletRequest request,HttpServletResponse response)
 {
	 boolean isok=false;
	 
	 String bbsUsername = userType  + bbsUsernameHomeSite;
	 //md5 加密后的32位的密码
	 String bbsPasswordMD5 = DiscuzEncryption.generateKey(bbsPassword, "MD5");
	 
	 //获取到用户的ip
	 String userip=request.getRemoteAddr();
	 
	 //获取当前时间
	 Long time = System.currentTimeMillis();
	 time=1228299264l;
	 
	 
	 //将数据插入到现有bbs的表中.
	 StringBuffer insertIntoBBSSql=new StringBuffer("insert into  cdb_members (username,password,groupid,regip,regdate,lastip,lastvisit,lastactivity,lastpost,email) values( ");
	 insertIntoBBSSql.append("'"+bbsUsername+"','"+bbsPasswordMD5+"',10,'"+userip+"',"+time+",'"+userip+"',"+time+","+time+","+time+",'"+email+"' )");
     
	 this.getJdbcTemplateForBBS().execute(insertIntoBBSSql.toString());
	 
	 
	 return isok;
	 
	 
 }

 
 
 /****
  * 通过用户名,获取用户的用户名,密码,邮件等信息
  * map的键值是,username,password,email
  */
 public Map  loadUserMessageByUsername(String username)
 {
	  Map ret =new HashMap();
	  StringBuffer searchSql= new StringBuffer(" select uid , username,password,email from cdb_members where username='"+username+"'");
	  
	  List li = this.getJdbcTemplateForBBS().queryForList(searchSql.toString());
	  if(li!=null  && !li.isEmpty())
	  {
		  Object[] obj = (Object[])li.get(0);
		  ret.put("username", obj[0]);
		  ret.put("password", obj[1]);
		  ret.put("email", obj[2]);
	 }
	  return ret;
 }
 
 
 
 /*******
  * 测试
  * @param arg
  */
 
 public static void main(String[] arg)
 {
	  DiscuzPassport  discuzPassport = new DiscuzPassport();
	  //discuzPassport.userBBSLogin("admin","qqddcAdmin20081127","zfs2012@yahoo.com.cn","http://www.qqddc.com",null,null);
	 // discuzPassport.userBBSLoginOut("admin","qqddcAdmin20081127","zfs2012@yahoo.com.cn","http://www.qqddc.com",null,null);
 }

public JdbcTemplate getJdbcTemplateForBBS() {
	return jdbcTemplateForBBS;
}

public void setJdbcTemplateForBBS(JdbcTemplate jdbcTemplateForBBS) {
	this.jdbcTemplateForBBS = jdbcTemplateForBBS;
}
 
 
// public static void main(String[] arg)
// {
//	  
//	    try {
//			Map mb = new LinkedHashMap();
//			mb.put("time", "" + System.currentTimeMillis());
//			mb.put("username", "admin");
//			mb.put("password", "qqddcAdmin20081127");
//			mb.put("email", "zfs2012@yahoo.com.cn");
//			
//			String key = "qqddcebb365"; //私钥
//			String enc=DiscuzPassport.passportEncode(mb);
//			String auth = DiscuzPassport.encrypt(enc, key);
//			 
//			String forward="http://www.qqddc.com";
//			
//			String verify = "login" + auth + forward + key;
//			verify = DiscuzEncryption.generateKey(verify, "MD5"); 
// 
//			String location = "http://www.qqddc.com/bbs/api/passport.php?action=login&auth=" + java.net.URLEncoder.encode(auth, "UTF-8") + "&forward=" +java.net.URLEncoder.encode(forward, "UTF-8")  + "&verify=" + verify;
//			System.out.println("链接:\n\n"+location);
//			
//			                   
//			String verifyOut = "logout"  + forward + key;
//			verifyOut = DiscuzEncryption.generateKey(verifyOut,"MD5");   
//			 
//			String locationOut = "http://www.qqddc.com/bbs/api/passport.php?action=logout"+ "&forward=" + java.net.URLEncoder.encode(forward, "UTF-8") + "&verify=" + verifyOut;
//			System.out.println("退出链接:\n\n"+locationOut);
//
//			
//			
//		} catch (UnsupportedEncodingException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
// }
 
}
